#include "smtptaskthread.h"

SmtpTaskThread::SmtpTaskThread() {}

/**
 * 如果socket断网,或者有一个命令出错,应该放弃整个队列.
 * TODO: 在执行一个任务时,如何关联一个函数,让外界/ui,显示一下更新,表明当前执行的进度?
 * TODO2: 如何写一个程序,向微信里发送一个消息?
 * @brief SmtpTaskThread::run
 */
void SmtpTaskThread::run()  {
    while(1){
        // qDebug() << "hello";

        if(taskQueue.length() == 0) {
            QThread::sleep(1);
            continue;
        }
        SmtpTask * task = taskQueue.dequeue();
        this->executeTask(task);
    }
}

/**
 * 将任务加入到队列等待执行.
 * @brief SmtpTaskThread::addTask
 * @param task
 */
void SmtpTaskThread::addTask(SmtpTask * task) {
    taskQueue.enqueue(task);
}

void SmtpTaskThread::executeTask(SmtpTask * task) {
    switch(task->type) {
    case 1:{
        qDebug()<< "connect to server" + this->server + QString::number(this->port);
        this->mSocket = new QTcpSocket(this);
        this->mSocket->connectToHost(this->server,this->port);
        if(this->mSocket->waitForConnected()){
            qDebug() << "connnected";
            this->readSocketSync();
        }
        else {
            qDebug() << "time out";
        }
        break;
    }
    default:{
        QString cmd = task->cmd;
        this->mSocket->write(cmd.toUtf8().constData());
        this->mSocket->flush();
        QString fmt("[C] [sending cmd:%1]");
        QString str = fmt.arg(cmd);
        qDebug()<< str;
        this->readSocketSync();
        //socket超时,task执行失败.
        break;
    }
    }


}

void SmtpTaskThread::readSocketSync() {
    // -1 代表等待无限.
    if(mSocket->waitForReadyRead(30000)) {
        QByteArray buffer = this->mSocket->readAll();
        QString str = "" + buffer;
        QString fmt("[S] [receive res:%1]");
        QString info = fmt.arg(str);
        qDebug() << info;
    }
}

